package com.wjk.cms.common;


import com.wjk.cms.exception.ApplicationException;

import com.wjk.cms.pojo.User;


import com.wjk.cms.service.TokenService;
import com.wjk.cms.service.UserService;
import com.wjk.cms.util.CommonUtil;
import com.wjk.cms.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class AuthControllerHelper {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;




    public User registerUser( String invitationCode, String phone, String... wxData) {


        if (StringUtils.isEmpty(invitationCode)) {
            throw new ApplicationException("请提供推广码");
        }

        String parentCode = invitationCode;

        // 注册
        User user = new User();


        user.setSalt(BCrypt.gensalt());
        user.setPassword(BCrypt.hashpw("123456", user.getSalt()));

        user.setStatus("0"); // 可展业


        user.setPhone(phone);

        // 微信信息
        if (wxData != null && wxData.length > 2) {

            user.setNickname(CommonUtil.cleanUtf8Mb4Characters(wxData[1]));
            user.setHeadPortrait(wxData[2]);
            user.setUnionid(wxData[0]);
        }


        userService.save(user);


        return user;
    }






    public Result loadUserInfo(HttpServletRequest request, Result result,  User user, boolean withoutToken) {
        if (!withoutToken) {
            result.add("token", tokenService.getToken(user));
        } else {
            if (request != null) {
                result.add("token", request.getHeader("token")); // 此接口必须原样返回token，以兼容老版本应用
            }
        }
        result.add("user", user);
        return result;
    }

    public Result loadUserInfo(HttpServletRequest request, Result result, User user) {
        return loadUserInfo(request, result, user, false);
    }





}
